#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "app_common.h"

int sprt_num(int num)
{
    sleep(1);
    return num*num;
}

void *sqrt_num_thread(void *arg)
{
    sleep(1);
    /* 1 强转 */
    int *num_p = (int *)arg;
    /* 2 解引用 取值 */
    int num = *num_p;
    /* 计算 */
    int res  = num * num;
    /* 4 开空间 */
    int *res_p = (int *)malloc(sizeof(int));
    /* 5 赋值 */
    *res_p = res;
    return res_p;
}

int main(int argc, char const *argv[])
{
    int num[5] = {1, 2, 3, 4, 5};
    int res[5];
    int sum = 0;
    long start_ts = app_common_get_cur_ts();

    /* 计算每个数的平方值 */
    pthread_t thread_id[5];
    for (int i = 0; i < 5; i++)
    {
        pthread_create(&thread_id[i], NULL, sqrt_num_thread, &num[i]);
    }
    for (int i = 0; i < 5; i++)
    {
        void *res_p;
        pthread_join(thread_id[i], &res_p);
        /* 强转 */
        int *res_p_int = (int *)res_p;
        /* 解引用 取值 */
        res[i] = *res_p_int;
    }

    /* 把计算结果汇总 */
    for (int i = 0; i < 5; i++)
    {
        sum += res[i];
    }
    long end_ts = app_common_get_cur_ts();
    printf("sum=%d, cost=%ld\n", sum, end_ts - start_ts);

    return 0;
}